package com.ziyueyuwen.xiniao.spi.impl;

import com.alibaba.fastjson.JSON;
import com.ziyueyuwen.xiniao.bean.homework.AnswerData;
import com.ziyueyuwen.xiniao.bean.homework.QuestionInfo;
import com.ziyueyuwen.xiniao.spi.QuestionTypeService;

import java.util.List;
import java.util.TreeMap;

import static com.ziyueyuwen.xiniao.enums.QuestionTypeEnum.MULTIPLE_CHOICE;

/**
 * @author jun 2018/12/18.
 */
public class MultipleChoiceImpl implements QuestionTypeService {

    @Override
    public void saveAnswer(String answerData, Integer questionNum, QuestionInfo questionInfo, List<AnswerData> answerDataList) {
        if (questionInfo.getQuestionType() == MULTIPLE_CHOICE) {
            answerData = answerData.toUpperCase();
            List<String> dataList = JSON.parseArray(answerData, String.class);
            AnswerData answerDataBean = new AnswerData();
            answerDataBean.setQuestionType(MULTIPLE_CHOICE);
            answerDataBean.setTotalScore(getTotalScore(questionInfo.getScoreMap()));
            answerDataBean.setObjectiveAnswerList(dataList);
            answerDataBean.setCorrectScore(getCorrectScore(dataList, questionInfo));
            if (answerDataList.size() < questionNum) {
                answerDataList.add(answerDataBean);
            } else {
                answerDataList.set(questionNum - 1, answerDataBean);
            }
        }
    }

    /**
     * 获取得分, 多选题判分规则, 错选不得分, 漏选得部分分值
     *
     * @param studentAnswerList List<String>
     * @param questionInfo      QuestionInfo
     * @return Integer
     */
    private Integer getCorrectScore(List<String> studentAnswerList, QuestionInfo questionInfo) {
        List<String> correctAnswerList = questionInfo.getAnswerList();
        TreeMap<String, Integer> scoreMap = questionInfo.getScoreMap();
        int correctNum = 0;
        for (String s : studentAnswerList) {
            if (!correctAnswerList.contains(s)) {
                // 错选直接返回0分
                return 0;
            }
            correctNum++;
        }
        if (scoreMap.containsKey(String.valueOf(correctNum))) {
            return scoreMap.get(String.valueOf(correctNum));
        }
        return 0;
    }

    /**
     * 获取小题的分数
     *
     * @param scoreMap TreeMap<String, Integer>
     * @return Integer
     */
    private Integer getTotalScore(TreeMap<String, Integer> scoreMap) {
        int totalScore = 0;
        for (int i : scoreMap.values()) {
            totalScore = Math.max(totalScore, i);
        }
        return totalScore;
    }

}
